package com.atguigu.flink10;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.kafka.clients.producer.ProducerConfig;

/**
 * @author Felix
 * @date 2024/3/1
 * 从指定的网络端口读取数据，发送到kafka的first主题
 * 要想保证Sink的精准一次，需要做如下操作
 *      .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE) 底层才会开启事务，使用2pc
 *      .setTransactionalIdPrefix("Flink02_2pc_Sink")
 *      开启检查点
 *      设置事务的超时时间
 *          检查点超时时间 < 设置事务的超时时间 <= 事务最大超时时间(默认15min)
 */
public class Flink02_2pc_Sink {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.enableCheckpointing(10000L, CheckpointingMode.EXACTLY_ONCE);
        //env.getCheckpointConfig().setCheckpointTimeout(60000L);
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);

        KafkaSink<String> kafkaSink = KafkaSink.<String>builder()
                .setBootstrapServers("hadoop102:9092")
                .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                        .setTopic("first")
                        .setValueSerializationSchema(new SimpleStringSchema())
                        .build()
                )
                .setDeliveryGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .setTransactionalIdPrefix("Flink02_2pc_Sink")
                .setProperty(ProducerConfig.TRANSACTION_TIMEOUT_CONFIG,15*60*1000 + "")
                .build();
        socketDS.sinkTo(kafkaSink);

        env.execute();
    }
}
